package com.example.mapdemo;

import java.lang.reflect.Field;

import android.Manifest;
import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.gy.paidao.MyApplication;
import com.gy.paidao.create.CreateBabbleActivity;
import com.gy.paidao.main.HomeActivity;
import com.gy.paidao.main.NotifyActivity;
import com.gy.paidao.person.LoginActivity;
import com.gy.paidao.setting.SettingMainActivity;
import com.gy.paidao.util.AnimUtil;
import com.gy.paidao.util.GoogleLocationUtil;
import com.gy.paidao.util.KeyBoard;
import com.gy.paidao.util.SPHelper;
import com.nostra13.universalimageloader.core.ImageLoader;

public class MainActivity extends TabActivity implements OnClickListener, View.OnLayoutChangeListener {

    private LinearLayout llMain,llButtom;
    private ImageView imgLeft, imgRight, imgCenter, imgDelete;
    private View viewEmpty, viewHome;
    private LinearLayout llSearch;
    private EditText etSearch;
    private TextView tvTitle;
    private ImageView imgHead;//头像
    private TextView tvName, tvHome, tvNotifications, tvSet, tvHelp, tvLogout;
    private RelativeLayout main_top;
    private LinearLayout ll_home, ll_notify, ll_map;
    private ImageView img_home, img_notify, img_map;
    private Intent mHomeIntent, mNotifyIntent, mMapIntent;
    private final String TAB_HOME = "HomeActivity";
    private final String TAB_NOTIFY = "NotifyActivity";
    private final String TAB_MAP = "BasicMapDemoActivity";
    private TabHost tabHost;
    private int intoSelect = 2, intoSecond;
    private Intent intent;
    private PopupWindow popupWindow;
    public  int width, height;

    private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            if ("refresh_main_tab".equals(intent.getAction())) {
                int posi = intent.getIntExtra("main_tab_posi", 1);
                setCurrentActivity(posi);
            }
            if ("finish_main".equals(intent.getAction())) {
                MainActivity.this.finish();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mains);
        this.tabHost = getTabHost();
        intoSelect = this.getIntent().getIntExtra("into_tab", 1);
        intoSecond = this.getIntent().getIntExtra("into_second", 0);
        IntentFilter filter = new IntentFilter();
        filter.addAction("refresh_main_tab");
        filter.addAction("finish_main");
        registerReceiver(receiver, filter);
        InitViews();
        InitIntent();
        setupIntent();
        getWindowHW();
        setViews();
        checkPermission();
//        setCurrentActivity(intoSelect);
        this.tabHost.setCurrentTabByTag(TAB_HOME);
    }

    private void InitViews() {
        ll_home = (LinearLayout) findViewById(R.id.activity_main_ll_home);
        ll_notify = (LinearLayout) findViewById(R.id.activity_main_ll_notify);
        ll_map = (LinearLayout) findViewById(R.id.activity_main_ll_map);
        img_home = (ImageView) findViewById(R.id.activity_main_img_home);
        img_notify = (ImageView) findViewById(R.id.activity_main_img_nofity);
        img_map = (ImageView) findViewById(R.id.activity_main_img_map);

        ll_home.setOnClickListener(this);
        ll_notify.setOnClickListener(this);
        ll_map.setOnClickListener(this);
    }

    private void InitIntent() {
        mHomeIntent = new Intent(MainActivity.this, HomeActivity.class);
        mMapIntent = new Intent(MainActivity.this, BasicMapDemoActivity.class);
        mNotifyIntent = new Intent(MainActivity.this, NotifyActivity.class);

    }

    private void setupIntent() {
        TabHost localTabHost = this.tabHost;
        try {
            Field current = tabHost.getClass().getDeclaredField("mCurrentTab");
            current.setAccessible(true);
            current.setInt(tabHost, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }

        localTabHost.addTab(buildTabSpec(TAB_NOTIFY, TAB_NOTIFY, mNotifyIntent));
        localTabHost.addTab(buildTabSpec(TAB_HOME, TAB_HOME, mHomeIntent));
        localTabHost.addTab(buildTabSpec(TAB_MAP, TAB_MAP, mMapIntent));

        try {
            Field current = tabHost.getClass().getDeclaredField("mCurrentTab");
            current.setAccessible(true);
            current.set(tabHost, -1);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void setCurrentActivity(int index) {
        switch (index) {
            case 1:
                onClick(ll_notify);
                break;
            case 2:
                onClick(ll_home);
                break;
            case 3:
                onClick(ll_map);
                break;
        }
    }


    private TabHost.TabSpec buildTabSpec(String tag, String resLabel,
                                         final Intent content) {
        return this.tabHost.newTabSpec(tag).setIndicator(resLabel)
                .setContent(content);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.activity_main_ll_notify:
                imgLeft.setVisibility(View.INVISIBLE);
                setViewNormal();
                this.tabHost.setCurrentTabByTag(TAB_NOTIFY);
                img_notify.setImageResource(R.mipmap.ic_notification_pressed);
                break;
            case R.id.activity_main_ll_home:
                imgLeft.setVisibility(View.VISIBLE);
                setViewNormal();
                this.tabHost.setCurrentTabByTag(TAB_HOME);
                img_home.setImageResource(R.mipmap.ic_home_pressed);
                break;
            case R.id.activity_main_ll_map:
                imgLeft.setVisibility(View.INVISIBLE);
                setViewNormal();
                this.tabHost.setCurrentTabByTag(TAB_MAP);
                img_map.setImageResource(R.mipmap.ic_map_pressed);
                break;
            case R.id.main_top_left:
                if(llSearch.getVisibility() == View.VISIBLE){
                    llSearch.setVisibility(View.GONE);
                    KeyBoard.demissKeyBoard(this,etSearch);
                } else {
                    llSearch.setVisibility(View.VISIBLE);

                    etSearch.setFocusable(true);
                    etSearch.setFocusableInTouchMode(true);
                    etSearch.requestFocus();
                    KeyBoard.showKeyBoard(this, etSearch);
                    InputMethodManager inputManager = (InputMethodManager) etSearch
                            .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(etSearch, 0);
                }

                break;
            case R.id.main_top_right:
                intent = new Intent(this, CreateBabbleActivity.class);
                startActivity(intent);
                break;
            case R.id.main_top_center:
                popupWindow.showAsDropDown(main_top);
                break;
            case R.id.main_img_delete:
                intent = new Intent("search_activity");
                intent.putExtra("search", "");
                MainActivity.this.sendBroadcast(intent);
                etSearch.setText("");
                llSearch.setVisibility(View.GONE);
                KeyBoard.demissKeyBoard(this, etSearch);
                break;
            case R.id.main_view_search_empty:
                llSearch.setVisibility(View.GONE);
                KeyBoard.demissKeyBoard(this, etSearch);
                break;
            case R.id.fg_home_tv_home:
                popupWindow.dismiss();
                break;
            case R.id.fg_home_tv_notification:

                break;
            case R.id.fg_home_tv_setting:
                intent = new Intent(this, SettingMainActivity.class);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(this);
                break;
            case R.id.fg_home_tv_help:

                break;
            case R.id.fg_home_tv_logout:
                intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(this);
                SPHelper.getInstance(MainActivity.this).setStringData("userLoginID", "");
                this.finish();
                break;
        }
    }


    private void setViewNormal() {
        img_home.setImageResource(R.mipmap.ic_home_normal);
        img_notify.setImageResource(R.mipmap.ic_notification_normal);
        img_map.setImageResource(R.mipmap.ic_map_normal);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    private void setViews() {
        llMain = (LinearLayout) findViewById(R.id.main_ll);
        llButtom = (LinearLayout) findViewById(R.id.main_ll_buttom);
        viewHome = View.inflate(this, R.layout.fg_home_layout, null);
        imgHead = (ImageView) viewHome.findViewById(R.id.fg_home_img_head);
        tvName = (TextView) viewHome.findViewById(R.id.fg_home_tv_name);
        tvHome = (TextView) viewHome.findViewById(R.id.fg_home_tv_home);
        tvNotifications = (TextView) viewHome.findViewById(R.id.fg_home_tv_notification);
        tvSet = (TextView) viewHome.findViewById(R.id.fg_home_tv_setting);
        tvHelp = (TextView) viewHome.findViewById(R.id.fg_home_tv_help);
        tvLogout = (TextView) viewHome.findViewById(R.id.fg_home_tv_logout);

        main_top = (RelativeLayout) findViewById(R.id.main_top);
        imgLeft = (ImageView) findViewById(R.id.main_top_left);
        imgRight = (ImageView) findViewById(R.id.main_top_right);
        imgCenter = (ImageView) findViewById(R.id.main_top_center);
        imgDelete = (ImageView) findViewById(R.id.main_img_delete);
        llSearch = (LinearLayout) findViewById(R.id.main_ll_search);
        etSearch = (EditText) findViewById(R.id.main_et_search);
        viewEmpty = findViewById(R.id.main_view_search_empty);
        tvTitle = (TextView) findViewById(R.id.main_top_title);

        imgLeft.setOnClickListener(this);
        imgRight.setOnClickListener(this);
        imgCenter.setOnClickListener(this);
        imgDelete.setOnClickListener(this);
        viewEmpty.setOnClickListener(this);

        tvHome.setOnClickListener(this);
        tvNotifications.setOnClickListener(this);
        tvSet.setOnClickListener(this);
        tvHelp.setOnClickListener(this);
        tvLogout.setOnClickListener(this);

        initPop();

        llMain.addOnLayoutChangeListener(this);
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String search = etSearch.getText().toString().trim();
                    if(TextUtils.isEmpty(search)){
                        llSearch.setVisibility(View.GONE);
                    } else {
                        KeyBoard.demissKeyBoard(MainActivity.this,etSearch);
                        viewEmpty.setVisibility(View.GONE);
                        intent = new Intent("search_activity");
                        intent.putExtra("search", search);
                        MainActivity.this.sendBroadcast(intent);
                    }
                    return true;
                }
                return false;
            }
        });

        etSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(hasFocus){
                    viewEmpty.setVisibility(View.VISIBLE);
                }
            }
        });

        if(MyApplication.loginBean != null &&
                !TextUtils.isEmpty(MyApplication.loginBean.headPortrait)){
            ImageLoader.getInstance().displayImage(MyApplication.loginBean.headPortrait,imgHead);
        }

        if(MyApplication.loginBean != null &&
                !TextUtils.isEmpty(MyApplication.loginBean.nickname)){
            tvName.setText(MyApplication.loginBean.nickname);
        }

    }

    private void initPop() {
        popupWindow = new PopupWindow(this);
        popupWindow.setContentView(viewHome);
        popupWindow.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.FILL_PARENT);
        popupWindow.setFocusable(true);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0x90000000);
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
    }

    /**
     * 获得手机分辨率
     */
    public void getWindowHW() {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        width = dm.widthPixels;
        height = dm.heightPixels;
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        int keyHeight = height / 3;
        //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
            llButtom.setVisibility(View.GONE);
        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
            llButtom.setVisibility(View.VISIBLE);
        }
    }

    private void openGPSSettings() {
        LocationManager alm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            return;
        } else {
            Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
            this.startActivityForResult(intent,0); //此为设置完成后返回到获取界面
        }

    }

    private void checkPermission(){
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    0);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0){
            GoogleLocationUtil.getInstance(getApplicationContext()).addLocationListener(new GoogleLocationUtil.OnLocationListener() {
                @Override
                public void onAmapLocationListener(Location aMapLocation) {
                    MyApplication.CURRENT_X = aMapLocation.getLongitude() + "";
                    MyApplication.CURRENT_Y = aMapLocation.getLatitude() + "";
                }

                @Override
                public void onAmapLocationFail() {

                }
            });
        }
    }
}
